# #!/usr/bin/env python3
# # -*- coding: utf-8 -*-
# # @Time    : 2020/12/11 14:35
# # @Author  : Wang Feng
# # @FileName: passport.py
# # @Software: PyCharm
# import re
#
# from flask import Blueprint, request, jsonify, current_app, session
# from sqlalchemy.exc import IntegrityError
#
# from app import redis_store
# from app.ext import db
# from app.models import User
# from app.utils.response_code import RET
#
# passport = Blueprint('passport', __name__)
#
#
# @passport.route('/register', methods=['POST'])
# def register():
#     """注册
#     请求的参数：手机号、短信验证码、密码、确认密码
#     参数格式：json
#     """
#     req_dict = request.get_json()
#     mobile = req_dict.get('mobile')
#     sms_code = req_dict.get('sms_code')
#     password = req_dict.get('password')
#     password2 = req_dict.get('password2')
#
#     # 校验参数
#     if not all([mobile, sms_code, password]):
#         return jsonify(code=RET.PARAMERR, msg='参数不完整')
#
#     # 判断手机号格式
#     if not re.match(r'1[34578]\d{9}', mobile):
#         # 表示格式不对
#         return jsonify(code=RET.PARAMERR, msg='手机号格式错误')
#
#     # 判断密码
#     if password != password2:
#         return jsonify(code=RET.PARAMERR, msg='两次密码不一致')
#
#     # 从redis中取出短信验证码
#     try:
#         real_sms_code = redis_store.get('sms_code_%s' % mobile)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(code=RET.DBERR, msg='读取真实短信验证码异常')
#
#     # 判断短信验证码是否过期
#     if real_sms_code is None:
#         return jsonify(code=RET.NODATA, msg='短信验证码失效')
#
#     # 删除redis中的短信验证码，防止重复使用校验
#     try:
#         redis_store.delete('sms_code_%s' %mobile)
#     except Exception as e:
#         current_app.logger.error(e)
#
#     # 判断用户填写的短信验证码的正确性
#     if real_sms_code != sms_code:
#         return jsonify(code=RET.DATAERR, msg='短信验证码错误')
#     # # 判断用户的手机号是否注册过
#     # try:
#     #     user = User.query.filter_by(mobile=mobile).first()
#     # except Exception as e:
#     #     current_app.logger.error(e)
#     #     return jsonify(code=RET.DATAERR, msg='数据库异常')
#     # else:
#     #     if user is not None:
#     #         # 表示手机号已存在
#     #         return jsonify(code=RET.DATAEXIST, msg='手机号已存在')
#
#     # 保存用户的注册数据到数据库中
#     user = User(name=mobile, mobile=mobile, password_hash=password)
#     # 设置密码
#     user.password = password
#     try:
#         db.session.add(user)
#         db.session.commit()
#     except IntegrityError as e:
#         # 数据库操作错误后的回滚
#         db.session.rollback()
#         # 表示手机号出现了重复值，即手机号已经注册过
#         current_app.logger.error(e)
#         return jsonify(code=RET.DATAEXIST, msg='手机号已存在')
#     except Exception as e:
#         # 数据库操作错误后的回滚
#         db.session.rollback()
#         current_app.logger.error(e)
#         return jsonify(code=RET.DBERR, msg='查询数据库异常')
#
#     # 保存登录状态到session中
#     session['name'] = mobile
#     session['mobile'] = mobile
#     session['id'] = user.id
#
#     # 返回结果
#     return jsonify(code=RET.OK, msg='注册成功')
#
